//
//  CLUIBaseViewController.m
//  CityHunter
//
//  Updated by xcq on 14-10-22.
//  Copyright (c) 2014年 CieNet. All rights reserved.
//

#import "CLUIBaseViewController.h"
#import "ConfigDefine.h"
#import "PublicDefine.h"
#import "Common.h"
#import "UIBarButtonItem+Badge.h"

 #define kNavigationBtnSpaceHorizontal 5.0f
#define kNavigationBtnSpaceVertical 10.0f
#define kNavigationBtnHeight (self.navigationController.navigationBar.frame.size.height - 2 * kNavigationBtnSpaceVertical)

#define BACKIMAGE @"fanhui"
#define BADGEIMG @"tasklist_title_infotip_red"

@interface CLUIBaseViewController () <UIGestureRecognizerDelegate>

@property (nonatomic, retain) NSArray *requestList;

@property (nonatomic, retain) UIView *maskView;
@property (nonatomic, retain) __block MBProgressHUD *progressHUD;
@property (nonatomic, retain) UITapGestureRecognizer *keyboardHideGr;

@end

@implementation CLUIBaseViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
 
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     [UIColor whiteColor], NSForegroundColorAttributeName,
                                                                 //    [UIFont systemFontOfSize:], NSFontAttributeName,
                                                                     nil]];
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //由于IOS8中定位的授权机制改变 需要进行手动授权
        self.locationManager = [[CLLocationManager alloc] init];
        //获取授权认证
        [self.locationManager requestAlwaysAuthorization];
        [self.locationManager requestWhenInUseAuthorization];
    }

}
- (void)setUp{
    
    [self setNavBarBgImgView:nil];
    
//    //添加键盘通知
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(keyboardWillShow:)
//                                                 name:UIKeyboardWillShowNotification object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(keyboardWillHide:)
//                                                 name:UIKeyboardWillHideNotification object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(keyboardWillChangeFrame:)
//                                                 name:UIKeyboardWillChangeFrameNotification object:nil];}
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //返回手势。
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    NSLog(@"enter: %@", NSStringFromClass([self class]));
    //[[AnalyticsManager sharedInstance] beginLogPageView:NSStringFromClass([self class])];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //[[AnalyticsManager sharedInstance] endLogPageView:NSStringFromClass([self class])];
}

- (void)didReceiveMemoryWarning
{
    NSLog(@"%@",[self class]);

    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) dealloc
{       NSLog(@"[%@ dealloc]",[self class]);
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - set navigation

- (void)showNavBarWithRightImage:(UIImage *)rimage
               andRightBtnAction:(SEL)raction
                   andRightBadge:(NSInteger)rnum
                    LeftBtnImage:(UIImage *)limage
                andLeftBtnAction:(SEL)laction
                     andLeftBage:(NSInteger)lnum
                           title:(NSString *)title
                        barColor:(UIColor *)color {
    if (limage) {
        UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [leftBtn setBackgroundImage:limage forState:UIControlStateNormal];
        if (laction) {
            [leftBtn addTarget:self action:laction forControlEvents:UIControlEventTouchUpInside];
        }
        leftBtn.tag = kNavigationBarLeftBtnTag;
        CGFloat height = kNavigationBtnHeight;
        CGFloat width = height * limage.size.width / limage.size.height;
        leftBtn.frame = CGRectMake(0,
                                   kNavigationBtnSpaceHorizontal,
                                   width,
                                   height);
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
        if (lnum > 0) {
            self.navigationItem.leftBarButtonItem.badgeValue = [NSString stringWithFormat:@"%ld",lnum];
            self.navigationItem.leftBarButtonItem.badgeBGColor = [UIColor redColor];
            self.navigationItem.rightBarButtonItem.badgeTextColor = [UIColor redColor];

        }
        
    }
    if (rimage) {
        UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [rightBtn setBackgroundImage:rimage forState:UIControlStateNormal];
        if (raction) {
            [rightBtn addTarget:self action:raction forControlEvents:UIControlEventTouchUpInside];
        }
        rightBtn.tag = kNavigationBarRightBtnTag;
        CGFloat height = kNavigationBtnHeight;
        CGFloat width = height * rimage.size.width / rimage.size.height;
        rightBtn.frame = CGRectMake(0,
                                    kNavigationBtnSpaceHorizontal,
                                    width,
                                    height);
        
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
        if (rnum > 0) {
            self.navigationItem.leftBarButtonItem.badgeValue = [NSString stringWithFormat:@"%ld",rnum];
            self.navigationItem.leftBarButtonItem.badgeBGColor = [UIColor redColor];
            self.navigationItem.rightBarButtonItem.badgeTextColor = [UIColor redColor];
        }
    }
    
    if (color) {
        [self.navigationController.navigationBar setBackgroundImage:nil
                                                      forBarMetrics:UIBarMetricsDefault];
        if ([self.navigationController.navigationBar respondsToSelector:@selector(setBarTintColor:)]) {
            self.navigationController.navigationBar.barTintColor = color;
        } else {
            self.navigationController.navigationBar.tintColor = GLOBAL_BARTINT_COLOR;
        }
    }
    [self showNavBarWithTitle:title];
}


- (void)showNavBarLeftImgAndRightTitle:(NSString*)title
                        andRightAction:(SEL)raction
                         andLeftAction:(SEL)laction
                           andLeftImge:(UIImage *)img{
    if (img) {
        UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [leftBtn setBackgroundImage:img forState:UIControlStateNormal];
        if (laction) {
            [leftBtn addTarget:self action:laction forControlEvents:UIControlEventTouchUpInside];
        }
        leftBtn.tag = kNavigationBarLeftBtnTag;
        CGFloat height = kNavigationBtnHeight;
        CGFloat width = height * img.size.width / img.size.height;
        leftBtn.frame = CGRectMake(0,
                                   kNavigationBtnSpaceHorizontal,
                                   width,
                                   height);
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
        
        
    }
    if (title) {
        UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [rightBtn setFrame:CGRectMake(15, kNavigationBtnSpaceHorizontal, 60, 30)];
        [rightBtn setTitle:title forState:UIControlStateNormal];
        [rightBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [rightBtn addTarget:self action:raction forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *rigthBar = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
        self.navigationItem.rightBarButtonItem = rigthBar;
    }
    [self.navigationController.navigationBar setBackgroundImage:nil
                                                  forBarMetrics:UIBarMetricsDefault];
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBarTintColor:)]) {
        self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    } else {
        self.navigationController.navigationBar.tintColor = GLOBAL_BARTINT_COLOR;
    }
    
}

- (void)showNavBarWithRightTitle:(NSString *)rightTitle
                  andRightAction:(SEL)raction
                   andLeftAction:(SEL)laction
                       andCustom:(BOOL) bol{
    //左边返回为箭头，右边是文字
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setBackgroundImage:[UIImage imageNamed:BACKIMAGE] forState:UIControlStateNormal];
    if (laction) {
        [leftBtn addTarget:self action:laction forControlEvents:UIControlEventTouchUpInside];
        
    }else{
        [leftBtn addTarget:self action:@selector(backTo) forControlEvents:UIControlEventTouchUpInside];
        
    }
    leftBtn.frame = CGRectMake(0,
                               kNavigationBtnSpaceHorizontal,
                               kNavigationBtnHeight * [UIImage imageNamed:BACKIMAGE].size.width / [UIImage imageNamed:BACKIMAGE].size.height,
                               kNavigationBtnHeight);
    UIBarButtonItem *leftBar = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftBar;
    
    if (bol) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, kNavigationBtnSpaceHorizontal, 80, 30)];
        label.text = rightTitle;
        label.textColor = [UIColor grayColor];
        
        UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [rightBtn setFrame:CGRectMake(15, kNavigationBtnSpaceHorizontal, 60, 30)];
        [rightBtn setTitle:rightTitle forState:UIControlStateNormal];
        [rightBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [rightBtn addTarget:self action:raction forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *rigthBar = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
        self.navigationItem.rightBarButtonItem = rigthBar;
        
    }
    
}

- (void)showNavBarWithTitle:(NSString *)title {
    if (title) {
        //LogInfo(@"self.navigationController.navigationItem %@", self.navigationController.navigationItem);
        //self.navigationController.navigationItem.title = title;
        self.title = title;
    }
}

- (void)setNavBarBgImgView:(NSString *)imageStr {
    self.navigationController.navigationBarHidden = NO;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    if ([Common systemVersion] == ESystemVer6OrLess) {
        if (!imageStr) {
            return;
            //imageStr = @"bg_title_ios6";
        }
    } else {
        if (!imageStr) {
            return;
            //imageStr = @"bg_title_ios7";
        }
        self.navigationController.navigationBar.translucent = NO;
    }
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage imageNamed:imageStr]
                                                                 imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
                                                  forBarMetrics:UIBarMetricsDefault];
}


- (void)backTo {
    if (self.navigationController) {
        [self.navigationController popViewControllerAnimated:YES];
     }
}

- (void)rightBtnAction {
    
}

#pragma mark - mask

- (void)displayMask {
    if (!self.maskView) {
        self.maskView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        //self.maskView.backgroundColor = [UIColor grayColor];
        //self.maskView.alpha = 0.8f;
        self.maskView.backgroundColor = [UIColor clearColor];
        self.maskView.alpha = 1.f;
    }
    if (!self.maskView.superview) {
        [self.view.window addSubview:self.maskView];
    }
 }

- (void)hideMask {
     if (self.maskView) {
        [self.maskView removeFromSuperview];
    }
}
- (void)displayProgressHUD {
    if (!self.progressHUD) {
         [CLProgressHUD showWaitAlertWithView:self.view.window];
     }
 }

- (void)hideProgressHUD {
    if (self.progressHUD) {
        [CLProgressHUD hideProgressHUDWithView:self.view.window];
    
     }
}

- (void)hideActionSheets {
    for (UIView *view in [[[UIApplication sharedApplication] keyWindow] subviews]) {
        if ([view isKindOfClass:[JGActionSheet class]]) {
            JGActionSheet *sheet = (JGActionSheet*)view;
            [sheet dismissAnimated:YES];
        }
    }
}

#pragma mark - network reuqest



- (void)showNavBarWithRightTitle:(NSString *)rightTitle andRightAction:(SEL)raction andLeftAction:(SEL)laction  andFontSize:(CGFloat)size andRightWidth:(CGFloat)width{
    
    //左边返回为箭头，右边是文字
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setBackgroundImage:[UIImage imageNamed:BACKIMAGE] forState:UIControlStateNormal];
    if (laction) {
        [leftBtn addTarget:self action:laction forControlEvents:UIControlEventTouchUpInside];
        
    }else{
        [leftBtn addTarget:self action:@selector(backTo) forControlEvents:UIControlEventTouchUpInside];
        
    }
    leftBtn.frame = CGRectMake(0,
                               kNavigationBtnSpaceHorizontal,
                               kNavigationBtnHeight * [UIImage imageNamed:BACKIMAGE].size.width / [UIImage imageNamed:BACKIMAGE].size.height,
                               kNavigationBtnHeight);
    UIBarButtonItem *leftBar = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftBar;
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setFrame:CGRectMake(15, kNavigationBtnSpaceHorizontal, width, 30)];
    [rightBtn setTitle:rightTitle forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:raction forControlEvents:UIControlEventTouchUpInside];
    [rightBtn.titleLabel setFont: [UIFont systemFontOfSize:size]];
    UIBarButtonItem *rigthBar = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rigthBar;
    
    
}


- (void)requestFailOption:(NSError*)error {
    if ([self isPresent]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[Common getLocalStr:@"NetworkRequestFail"]
                                                        message:[error.userInfo objectForKey:@"errorMsg" ]
                                                       delegate:self
                                              cancelButtonTitle:[Common getLocalStr:@"CommonTitleConfirm"]
                                              otherButtonTitles:nil, nil];
        alert.tag = kRequestFailRetBtnTag;
        [alert show];
    }
}

#pragma mark - Present

- (BOOL)isPresent {
    if (self.navigationController) {
        return self == self.navigationController.viewControllers.lastObject;
    }
    return YES;
}
// 
//
//- (UIViewController*)popToViewControllerKindClass:(id)viewControllerClass animated:(BOOL)animated {
//    if (!viewControllerClass) {
//        return nil;
//    }
//    
//    NSArray *arr;
//    if (![viewControllerClass isKindOfClass:[NSArray class]]) {
//        arr = [NSArray arrayWithObject:viewControllerClass];
//    } else {
//        arr = viewControllerClass;
//    }
//    
//    for (UIViewController *viewController in [self.navigationController.viewControllers reverseObjectEnumerator]) {
//        for (Class class in arr) {
//            if ([viewController isKindOfClass:class]) {
//                [self popToViewController:viewController animated:animated];
//                return viewController;
//            }
//        }
//    }
//    return nil;
//}
//
//  
// - (UIViewController*)popToViewControllerMemberClass:(id)viewControllerClass animated:(BOOL)animated {
//    if (!viewControllerClass) {
//        return nil;
//    }
//    
//    NSArray *arr;
//    if (![viewControllerClass isKindOfClass:[NSArray class]]) {
//        arr = [NSArray arrayWithObject:viewControllerClass];
//    } else {
//        arr = viewControllerClass;
//    }
//     
//    for (UIViewController *viewController in [self.navigationController.viewControllers reverseObjectEnumerator]) {
//        for (Class class in arr) {
//            if ([viewController isMemberOfClass:class]) {
//                [self popToViewController:viewController animated:animated];
//                return viewController;
//            }
//        }
//    }
//    
//    return nil;
//}

#pragma mark - 重新登录
//
//- (void)retryLogin {
//    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
//    StartViewController *start = [story instantiateViewControllerWithIdentifier:@"Start"];
//    start.startMode = StartModeRetry;
//    [self.navigationController pushViewController:start animated:NO];
//    [start performSegueWithIdentifier:@"startCustomPushLogin" sender:start];
//}

 #pragma mark - storyboard segua

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
}

- (IBAction)unwindSegue:(UIStoryboardSegue *)sender {
    NSLog(@"back to: %@", NSStringFromClass([self class]));
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark - keyboard

//隐藏虚拟键盘
- (void)hideKeyboard {
     if (self.editingTextInputView) {
        [self.editingTextInputView resignFirstResponder];
    } else {
        //[self keyboardWillHide:nil];
        //[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
    }
}

- (void)keyboardWillChangeFrame:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    
    // Get the origin of the keyboard when it's displayed.
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    // Get the top of the keyboard as the y coordinate of its origin in self's view's coordinate system. The bottom of the text view's frame should align with the top of the keyboard's final position.
    CGRect keyboardRect = [aValue CGRectValue];
    CGFloat keyboardHeight = keyboardRect.size.height;
    if (keyboardHeight > 0) {
        CGFloat viewHeight = CGRectGetHeight(self.view.bounds) - [self.view convertPoint:CGPointMake(0, GET_VIEW_BOTTOM(self.editingTextInputView)) fromView:self.editingTextInputView.superview].y;
        CGFloat riseHeight = keyboardHeight - (viewHeight - 2);

        if (riseHeight > 0) {
            [UIView animateWithDuration:0.5 animations:^(void){
                self.view.frame = CGRectOffset(self.view.frame, 0, -riseHeight);
            }];
        }
    }
}

//- (void)keyboardWillShow:(NSNotification *)notification {
//    if (!self.keyboardHideGr) {
//        self.keyboardHideGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
//        [self.view.window addGestureRecognizer:self.keyboardHideGr];
//    }
//}
//
//- (void)keyboardWillHide:(NSNotification *)notification {
//    self.editingTextInputView = nil;
//    [UIView animateWithDuration:0.5 animations:^(void){
//        self.view.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame));
//    }];
//    [self.view.window removeGestureRecognizer:self.keyboardHideGr];
//    self.keyboardHideGr = nil;
//}

#pragma mark - 网络请求代理
-(void)networkingStartHandleWithRequestIdentifier:(RequestIdentifier)identifier
{
    [self.view makeToastActivity];//现实加载中
    self.view.layer.cornerRadius = 8.0f;
    
}

-(void)networkingCompleteHandleWithRequestIdentifier:(RequestIdentifier)identifier
{
    [self.view hideToastActivity];//隐藏加载中
    
}

-(void)networkingFailureHandleWithRequestIdentifier:(RequestIdentifier)identifier errorMessage:(NSString *)message
{
    [self.view makeToast:message];
    
}


#pragma mark ----------------------------- ios7 兼容

#ifdef __IPHONE_7_0

//- (UIStatusBarStyle)preferredStatusBarStyle
//{
//    return UIStatusBarStyleLightContent;
//}


- (BOOL)prefersStatusBarHidden
{
    return NO;
}

#endif

@end
